/**
 *	Android RPG Miyazaki Quest<br>
 *	<br>
 *	Copyright (c) CGENE Inc. All Right Reserved.<br>
 *	http://cgene.jp/<br>
 *
 *	BGM	http://www.skipmore.com/sound/
 */

package com.cgene.game;

import java.io.*;
import java.util.*;

//import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

//import android.view.KeyEvent;
import android.util.Log;
import android.media.*;

@SuppressWarnings("unused")
public class MyUtil {

	static MediaPlayer mp_Bgm  = null;
	static int BGM_STATUS      = -1;
	static int Bgm_Playing_Now = -1;

	private static final String[]	BGM_Connection_URL =
	{
		"http://httptest.web.fc2.com/sht_a02.ogg",
		"http://httptest.web.fc2.com/sht_a03.ogg",
		"http://httptest.web.fc2.com/sht_a06.ogg",
	};

    final static public int BGM_TITLE  = 0;
    final static public int BGM_MAP    = 1;
    final static public int BGM_BATTLE = 2;

    static MediaPlayer mp_Se  = null;
    static int SE_STATUS	  = -1;
    static int Se_Playing_Now = -1;

	private static final String[]	SE_Connection_URL =
	{
		"R.raw.encount",
		"R.raw.attack_player",
		"R.raw.attack_player2",
		"R.raw.attack_enemy",
		"R.raw.levelup",
		"R.raw.in_out",
		"R.raw.magic"
	};

    final static public int SE_MAP_ENCOUNT			= 0;
    final static public int SE_BATTLE_ATTACK_PLAYER	= 1;
    final static public int SE_BATTLE_ATTACK_ENEMY	= 2;
    final static public int SE_BATTLE_LEVELUP		= 3;

    final static public int SE_IN_OUT				= 4;
    final static public int SE_CURE					= 5;
    final static public int SE_MAGIC				= 6;

    final static public int PlaySound_NG	  = -1;
    final static public int PlaySound_OK	  = 0;
    final static public int PlaySound_PLAYING = 1;

	public static String[] split(String strTarget, String token) {
		return strTarget.split("\\Q" + token + "\\E", -1);
	}

	@SuppressWarnings("unchecked")
	public static String replace(String strTarget, HashMap conv) {
		for (Iterator it = conv.entrySet().iterator(); it.hasNext();) {
			Map.Entry entry = (Map.Entry) it.next();
			strTarget = MyUtil.replace(strTarget, (String)entry.getKey(), (String)entry.getValue());
		}
		return strTarget;
	}

	public static String replace(String strTarget, String strOldStr, String strOldNew) {
		StringBuffer strResult = new StringBuffer();
		String[] strSplit = split(strTarget, strOldStr);
		strResult.append(strSplit[0]);
		for (int i = 1; i < strSplit.length; i ++) {
			strResult.append(strOldNew);
			strResult.append(strSplit[i]);
		}
		return strResult.toString();
	}

	public static String s2s(String s[], String separator) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < s.length; i ++) {
			if (i != 0) buf.append(separator);
			buf.append(s[i]);
		}
		return buf.toString();
	}

	@SuppressWarnings("unchecked")
	public static String a2s(ArrayList a, String separator) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < a.size(); i ++) {
			if (i != 0) buf.append(separator);
			buf.append((String)a.get(i));
		}
		return buf.toString();
	}

	@SuppressWarnings("unchecked")
	public static String[] a2s(ArrayList a) {
		String s[] = new String[a.size()];
		for (int i = 0; i < s.length; i ++) {
			s[i] = a.get(i).toString();
		}
		return s;
	}

	private static long cnt = 0;

	public static int nextInt(int k) {
		java.util.Date d = new java.util.Date();
		Random r = new Random(d.getTime()+cnt);
		long p = r.nextInt();
		cnt = p;
		return java.lang.Math.abs((int)p)%k;
	}

	@SuppressWarnings("unchecked")
	public static String getDebugText(Map map, String demi) {
		StringBuffer buf = new StringBuffer();
		for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
			Map.Entry entry = (Map.Entry) it.next();
			if (buf.length() != 0) buf.append(demi);
			Object o1 = entry.getKey();
			Object o2 = entry.getValue();
			if (o2 instanceof List) {
				buf.append(o1 + " = {" + getDebugText((List)o2, ", ") + "}");
			} else {
				buf.append(o1 + " = " + o2);
			}
		}
		return buf.toString();
	}

	@SuppressWarnings("unchecked")
	public static String getDebugText(java.util.List list, String demi) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < list.size(); i ++) {
			Object obj = list.get(i);
			if (buf.length() != 0) buf.append(demi);
			if (obj instanceof String[]) {
				String tmp[] = (String[])obj;
				for (int j = 0; j < tmp.length; j ++) {
					buf.append("[" + tmp[j] + "]");
				}
			} else {
				buf.append(obj);
			}
		}
		return buf.toString();
	}

	public static String getDebugText(String args[], String demi) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < args.length; i ++) {
			if (buf.length() != 0) buf.append(demi);
			buf.append(args[i]);
		}
		return buf.toString();
	}

	public static byte[] getFileByteArray(String file) throws Exception {
		return getFileByteArray(new File(file));
	}

	public static byte[] getFileByteArray(File file) throws Exception {
		BufferedInputStream bis = null;
		ByteArrayOutputStream baos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(file));
			baos = new ByteArrayOutputStream();
			byte buf[] = new byte[1024];
			int count;
			while ((count = bis.read(buf, 0, 1024)) != -1) {
				baos.write(buf, 0, count);
			}
			if (baos != null) {
				baos.flush();
				baos.close();
			}
			if (bis != null) {
				bis.close();
				bis = null;
			}
		} catch (Exception e) {
			try {
				if (baos != null) {
					baos.flush();
					baos.close();
				}
				if (bis != null) {
					bis.close();
					bis = null;
				}
			} catch (Exception ee) {
			}
		}
		if (baos != null) return baos.toByteArray();
		else return new byte[0];
	}

	public static boolean writeFile(String file, String body) throws Exception {
		return writeFile(file, body, "Shift_JIS", null);
	}

	public static boolean mkdirs(String file) throws Exception {
		int idx1 = file.indexOf(File.separatorChar);
		int idx2 = file.lastIndexOf(File.separatorChar);
		String dirs = new String();
		if (idx1 == -1) return true;
		else if (idx1 == 0 && idx1 == idx2) dirs = file;
		else if (idx1 == 0) dirs = file.substring(0, idx2);
		else dirs = file.substring(0, idx2);
		File dir = new File(dirs);
		boolean ret = dir.mkdirs();
		return ret;
	}

	public static boolean writeFile(String file, byte buf[]) throws Exception {
		boolean ret = false;
		FileOutputStream fos = null;
		mkdirs(file);
		try {
			fos = new FileOutputStream(new File(file));
			fos.write(buf);
			fos.flush();
			ret = true;
		} catch (Exception e) {
			ret = false;
		}
		if (fos != null) {
			try {
				fos.close();
				fos = null;
			} catch (Exception e) {
			}
		}
		return ret;
	}

	@SuppressWarnings("unchecked")
	public static boolean writeFile(String file, Object obj, String encoding, String sepa) throws Exception {
		boolean ret = false;
		mkdirs(file);

		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding));
		try {
			if (obj instanceof ArrayList) {
				bw.write(a2s((ArrayList)obj, sepa));
			} else if (obj instanceof Map) {
				bw.write(getDebugText((Map)obj, sepa));
			} else if (obj instanceof String[]) {
				bw.write(s2s((String[])obj, sepa));
			} else if (obj instanceof StringBuffer) {
				bw.write(obj.toString());
			} else {
				bw.write(obj.toString());
			}
			ret = true;
		} catch (Exception e) {
			ret = false;
		}
		if (bw != null) {
			try {
				bw.close();
				bw = null;
			} catch (Exception e) {
			}
		}
		return ret;
	}

	public static int PlaySound_BGM(MiyagiQuest activity, int BGM_STATUS) throws Exception
	{
		int ret = PlaySound_NG;

		if(BGM_STATUS == Bgm_Playing_Now) {
			ret = PlaySound_PLAYING;
        	return ret;
		}

		switch(BGM_STATUS)
		{
		case BGM_TITLE:
		case BGM_MAP:
		case BGM_BATTLE:
			Bgm_Playing_Now = BGM_STATUS;
			break;
		default:
			DebugLog.printin("BGM_STATUS:Error");
        	return ret;
		}

		if(mp_Bgm != null){
			DebugLog.printin("MediaPlayer:mp_Bgm.Release");
			mp_Bgm.stop();
			mp_Bgm.setOnPreparedListener(null);
			mp_Bgm.release();
			mp_Bgm = null;
		}

		URLConnection connection = new URL(BGM_Connection_URL[BGM_STATUS]).openConnection();
		InputStream is = connection.getInputStream();
		File file = new File(activity.getCacheDir(), "tmp");
		FileOutputStream fos = new FileOutputStream(file);
		byte buf[] = new byte[1024];
		do
		{
			int numread = is.read(buf);
			if (numread == -1) {
				break;
			}
			fos.write(buf, 0, numread);
		} while (true);
		fos.flush();
		fos.close();

		mp_Bgm = new MediaPlayer();

   	    DebugLog.printin("new mp_Bgm = "+mp_Bgm);

		mp_Bgm.setDataSource(new FileInputStream(file).getFD());
		mp_Bgm.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
		{
			//@Override
			public void onPrepared(MediaPlayer mp_Bgm)
			{
				try {
					DebugLog.printin("STATUS_TITLE");
					mp_Bgm.start();
					mp_Bgm.setLooping(true);
				} catch (Exception e) {
					Log.d("Error", e.getMessage());
					if(mp_Bgm != null) {
						DebugLog.printin("catch:MediaPlayer.release");
						mp_Bgm.stop();
						mp_Bgm.release();
						mp_Bgm = null;
					}
				}
			}
		});
		mp_Bgm.prepareAsync();

		ret = PlaySound_OK;
		return ret;
	}

	public static int PlaySound_SE(MiyagiQuest activity, int SE_STATUS) throws Exception
	{
		int ret = PlaySound_NG;

		if(mp_Se != null) {
			DebugLog.printin("PlaySound_SE:MediaPlayer.release");
			mp_Se.stop();
			mp_Se.release();
			mp_Se = null;
		}

		switch(SE_STATUS)
		{
		case SE_MAP_ENCOUNT:
			if(mp_Bgm != null) {
				DebugLog.printin("MediaPlayer:mp_Bgm.Release");
				mp_Bgm.stop();
				mp_Bgm.setOnPreparedListener(null);
				mp_Bgm.release();
				mp_Bgm = null;
			}
			Se_Playing_Now = SE_STATUS;
			mp_Se = MediaPlayer.create(activity, R.raw.encount);
			break;
		case SE_BATTLE_ATTACK_PLAYER:
			Se_Playing_Now = SE_STATUS;
			mp_Se = MediaPlayer.create(activity, R.raw.attack_player);
			break;
		case SE_BATTLE_ATTACK_ENEMY:
			Se_Playing_Now = SE_STATUS;
			mp_Se = MediaPlayer.create(activity, R.raw.attack_enemy);
			break;
		case SE_BATTLE_LEVELUP:
			Se_Playing_Now = SE_STATUS;
			mp_Se = MediaPlayer.create(activity, R.raw.levelup);
			break;

		case SE_IN_OUT:
			Se_Playing_Now = SE_STATUS;
			mp_Se = MediaPlayer.create(activity, R.raw.in_out);
			break;
		case SE_CURE:
			Se_Playing_Now = SE_STATUS;
			mp_Se = MediaPlayer.create(activity, R.raw.cure);
			break;
		case SE_MAGIC:
			Se_Playing_Now = SE_STATUS;
			mp_Se = MediaPlayer.create(activity, R.raw.magic);
			break;

		default:
			DebugLog.printin("SE_STATUS:Error");
        	return ret;
		}
		mp_Se.start();

		ret = PlaySound_OK;
		return ret;
	}
}